<template>
  <el-card header="基础信息" class="form-section">
    <el-form-item label="客户名称" prop="name" required>
      <el-input
        v-model="formData.name"
        placeholder="请输入客户名称"
        clearable
        maxlength="255"
        show-word-limit
        @focus="handleFocus"
        @blur="handleBlur"
      />
    </el-form-item>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="客户类型" prop="customer_type" required>
          <el-radio-group
            v-model="formData.customer_type"
            @change="handleTypeChange"
            @focus="handleRadioFocus"
            @blur="handleRadioBlur"
          >
            <el-radio :label="2">企业客户</el-radio>
            <el-radio :label="1">个人客户</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="联系电话" prop="phone" required>
          <el-input
            v-model="formData.phone"
            placeholder="请输入联系电话"
            clearable
            @input="handlePhoneInput"
            @focus="handleFocus"
            @blur="handleBlur"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="负责人" prop="user_id" required>
          <el-select
            v-model="formData.user_id"
            placeholder="请选择负责人"
            filterable
            clearable
            style="width: 100%"
            @change="handleUserChange"
            @focus="handleFocus"
            @blur="handleBlur"
          >
            <el-option
              v-for="user in userList"
              :key="user.value"
              :label="user.label"
              :value="user.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="所属部门" prop="department_id">
          <el-select
            v-model="formData.department_id"
            placeholder="请选择部门"
            clearable
            style="width: 100%"
            :disabled="!formData.user_id"
            @focus="handleFocus"
            @blur="handleBlur"
          >
            <el-option
              v-for="dept in deptList"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="客户来源" prop="source">
          <el-select
            v-model="formData.source"
            placeholder="请选择客户来源"
            clearable
            style="width: 100%"
            @focus="handleFocus"
            @blur="handleBlur"
          >
            <el-option
              v-for="item in sourceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客户等级" prop="level">
          <el-select
            v-model="formData.level"
            placeholder="请选择客户等级"
            style="width: 100%"
            @focus="handleFocus"
            @blur="handleBlur"
          >
            <el-option label="普通客户" :value="1" />
            <el-option label="重要客户" :value="2" />
            <el-option label="核心客户" :value="3" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="重要程度" prop="important_level">
          <el-select
            v-model="formData.important_level"
            placeholder="请选择重要程度"
            style="width: 100%"
            @focus="handleFocus"
            @blur="handleBlur"
          >
            <el-option label="普通" :value="1" />
            <el-option label="重要" :value="2" />
            <el-option label="关键" :value="3" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客户状态" prop="status">
          <el-select
            v-model="formData.status"
            placeholder="请选择客户状态"
            style="width: 100%"
            @focus="handleFocus"
            @blur="handleBlur"
          >
            <el-option label="潜在客户" :value="1" />
            <el-option label="跟进中" :value="2" />
            <el-option label="已合作" :value="3" />
            <el-option label="公海客户" :value="4" />
            <el-option label="已流失" :value="5" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, watch } from 'vue'
  import { customerApi } from '@/api/crm'
  import { ElMessage } from 'element-plus'

  const props = defineProps({
    modelValue: {
      type: Object,
      default: () => ({}),
    },
  })

  const emit = defineEmits(['change', 'update:modelValue'])

  // 双向绑定
  const formData = computed({
    get: () => props.modelValue,
    set: value => {
      emit('update:modelValue', value)
    },
  })

  // 数据列表
  const userList = ref<Array<{ value: number; label: string; department_id?: number }>>([])
  const deptList = ref<Array<{ value: number; label: string }>>([])
  const sourceOptions = ref<Array<{ value: string; label: string }>>([])

  // 防止标签点击事件标记
  const isLabelClicked = ref(false)

  // 加载数据
  const loadOptions = async () => {
    try {
      // 加载负责人列表
      const userRes = await customerApi.userOptions()
      userList.value = userRes.data || []

      // 加载部门列表
      const deptRes = await customerApi.departmentOptions()
      deptList.value = deptRes.data || []

      // 加载客户来源
      const sourceRes = await customerApi.sourceOptions()
      sourceOptions.value = sourceRes.data || []
    } catch (error: any) {
      // 忽略请求取消错误（组件卸载时的正常行为）
      if (error?.code === 'ERR_CANCELED') {
        return
      }
      console.error('获取选项数据失败:', error)
      ElMessage.error('获取选项数据失败')
    }
  }

  // 监听客户来源变化
  watch(
    () => formData.value.source,
    (newVal, oldVal) => {
      console.log('客户来源变化:', oldVal, '->', newVal)
      // 如果有值但选项还没加载，则强制加载选项
      if (newVal && sourceOptions.value.length === 0) {
        loadOptions()
      }
    }
  )

  // 处理标签点击事件
  const handleLabelClick = () => {
    console.log('标签被点击，标记为标签点击')
    isLabelClicked.value = true

    // 延迟重置标记，给其他事件时间处理
    setTimeout(() => {
      isLabelClicked.value = false
    }, 100)
  }

  // 处理控件聚焦事件
  const handleFocus = (event: any) => {
    console.log('控件聚焦事件', event)
    // 如果是标签点击引起的聚焦，可以在这里进行处理
    if (isLabelClicked.value) {
      console.log('标签点击引起的聚焦事件，已屏蔽')
      // 可以在这里添加特殊处理逻辑
    }
  }

  // 处理控件失焦事件
  const handleBlur = (event: any) => {
    console.log('控件失焦事件', event)
  }

  // 处理单选框聚焦事件
  const handleRadioFocus = (event: any) => {
    console.log('单选框聚焦事件', event)
    if (isLabelClicked.value) {
      console.log('标签点击引起的单选框聚焦事件，已屏蔽')
    }
  }

  // 处理单选框失焦事件
  const handleRadioBlur = (event: any) => {
    console.log('单选框失焦事件', event)
  }

  // 处理客户类型变化
  const handleTypeChange = (value: number) => {
    console.log('客户类型变化处理', value)

    emit('change', { field: 'customer_type', value })

    // 切换为企业客户时，代表人设为必填
    // 切换为个人客户时，清空企业信息
    if (value === 1) {
      // 清空企业信息
      formData.value.legal_person = ''
      formData.value.id_type = null
      formData.value.id_number = ''
      formData.value.industry = ''
      formData.value.scale = ''
    }

    emit('change', { field: 'form_data_changed', value: 'customer_type_toggle' })
  }

  // 处理负责人变化
  const handleUserChange = (value: number) => {
    console.log('负责人变化处理', value)

    // 清空部门
    if (value !== formData.value.department_id) {
      formData.value.department_id = 0
    }

    // 重新加载部门选项
    if (value) {
      // 获取选中的用户信息，更新部门
      const selectedUser = userList.value.find(user => user.value === value)
      if (selectedUser && selectedUser.department_id) {
        formData.value.department_id = selectedUser.department_id
      }
    }

    emit('change', { field: 'user_id', value })
  }

  // 处理电话号码变化
  const handlePhoneInput = (value: string) => {
    console.log('电话号码输入处理', value)
    emit('change', { field: 'phone', value })
  }

  // 组件挂载时加载数据
  onMounted(() => {
    loadOptions()
  })
</script>

<style scoped>
  .form-section {
    margin-bottom: 20px;
  }

  /* 防止标签点击的样式方案 */
  :deep(.el-form-item__label) {
    cursor: default;
    user-select: none;
  }

  /* 如果需要更严格的控制，可以给特定标签添加类 */
  :deep(.prevent-label-click .el-form-item__label) {
    cursor: default;
    user-select: none;
  }

  /* 单选按钮组标签样式 */
  :deep(.el-radio__label) {
    user-select: none;
  }

  /* 选择器标签样式 */
  :deep(.el-select .el-input__inner) {
    user-select: none;
  }
</style>
